//
//  AppDelegate.m
//  SleepNews
//
//  Created by Kavee DJ on 2016/12/8.
//  Copyright © 2016年 Kavee DJ. All rights reserved.
//

#import "AppDelegate.h"
#import "SNKTabBarController.h"
#import "KDJAdViewController.h"


#import <UserNotifications/UserNotifications.h>


#import "CYLPlusButtonSubclass.h"
#import "SNKTabBarControllerConfig.h"
#import <RESideMenu.h>
#import <AVOSCloudSNS.h>
#import <AVOSCloud.h>
#import <LCChatKit.h>
#import "LCChatKitExample.h"

#import "SNKAppConfig.h"
#import "SNKStartManager.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//微信SDK头文件
#import "WXApi.h"

//新浪微博SDK头文件
#import "WeiboSDK.h"

//#import "EMSDK.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@property (nonatomic, strong) NSArray *conversations;
@property (nonatomic, strong) SNKTabBarController *tabBarMain;

@end

@implementation AppDelegate

- (NSArray *)conversations
{
    if (!_conversations) {
        _conversations = [NSArray array];
    }
    return _conversations;
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [AVOSCloudSNS handleOpenURL:url];
}

// When Build with IOS 9 SDK
// For application on system below ios 9
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [AVOSCloudSNS handleOpenURL:url];
}
// For application on system equals or larger ios 9
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
    return [AVOSCloudSNS handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    
    //---------------------------------------- AVOSCloud ----------------------------------------------------
    // LeanCloud 注册
    [AVOSCloud setApplicationId:@"ifJV3V0wPapONXS0koJHEzuR-gzGzoHsz" clientKey:@"xsVr0qLcAizwb6sElu72uOW8"];
    
    // 数据分析
    [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
    
    // 第三方登录
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSSinaWeibo withAppKey:@"139626686" andAppSecret:@"2f5625d5f72b19126c43a4650796a5a7" andRedirectURI:@"http://www.baidu.com"];
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSQQ withAppKey:@"1105819119" andAppSecret:@"iVnj0MpqGXBD11Uw" andRedirectURI:nil];
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSWeiXin withAppKey:@"wx7b73d0064794d588" andAppSecret:@"2bf22d9f8bef01e1a9be57fa8202c7c4" andRedirectURI:nil];
    //---------------------------------------- AVOSCloud ----------------------------------------------------

    
    // 配置通知
    [self registerForRemoteNotification];
    // 初始化ChatKit
    [LCChatKitExample invokeThisMethodInDidFinishLaunching];
    
    
    //响应通知数据:当应用是被通知打开的时候 < 10.0
    /*
    if ([[UIDevice currentDevice].systemVersion floatValue] < 10.0) {
        NSDictionary *notificationPayload;
        @try {
            notificationPayload = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
        } @catch (NSException *exception) {}
        
        // Create a pointer to the Photo object
        NSString *photoId = [notificationPayload objectForKey:@"p"];
        AVObject *targetPhoto = [AVObject objectWithoutDataWithClassName:@"Photo"
                                                                objectId:photoId];
        
        // Fetch photo object
        [targetPhoto fetchIfNeededInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            // Show photo view controller
            if (!error && [AVUser currentUser]) {
//                PhotoVC *viewController = [[PhotoVC alloc] initWithPhoto:object];
//                [self.navController pushViewController:viewController animated:YES];
            }
        }];
    }
     */
    
    
    //---------------------------------------- 主界面 ----------------------------------------------------
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.tabBarMain = [[SNKTabBarController alloc] init];
//    KDJAdViewController *adVc = [[KDJAdViewController alloc] init];
    
    [CYLPlusButtonSubclass registerPlusButton];
    SNKTabBarControllerConfig *tab = [[SNKTabBarControllerConfig alloc] init];
    
    RESideMenu *sideMenuViewController = [[RESideMenu alloc] initWithContentViewController:tab.tabBarController leftMenuViewController:[[UIViewController alloc] init] rightMenuViewController:[[UIViewController alloc] init]];
    sideMenuViewController.backgroundImage = [UIImage  imageNamed:@"Stars"];

    self.window.rootViewController = sideMenuViewController;
    [self.window makeKeyAndVisible];
    //---------------------------------------- 主界面 ----------------------------------------------------


    //获取未读的消息数
//    [self loadConversations];
    
    // 分享SDK
    [self setupShareSDK];
    
    // 地理相关
    [SNKStartManager shareStartManager];
    [SNKAppConfig shareAppConfig];
    
    //开屏广告初始化并展示代码
    [self setUpAd];
    
    return YES;
}

- (void)setUpAd {
    GDTSplashAd *splashAd = [[GDTSplashAd alloc] initWithAppkey:@"1105886209" placementId:@"4020015868666983"];
    splashAd.delegate = self; //设置代理
    //根据iPhone设备不同设置不同背景图
    if (IS_IPHONE6PLUS) { // 6p
        splashAd.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LaunchImage-800-Portrait-736h@3x"]];
    } else if (IS_IPHONE6) { // 6
        splashAd.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LaunchImage-800-667h"]];
    } else if (IS_IPHONE5) { // 5
        splashAd.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LaunchImage-568h"]];
    } else if (IS_IPHONE4) { // 4
        splashAd.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LaunchImage-700"]];
    }
    
    //设置开屏拉取时长限制，若超时则不再展示广告
    splashAd.fetchDelay = 3;
    //拉取并展示全屏开屏广告
    [splashAd loadAdAndShowInWindow:self.window];
    self.splash = splashAd;
}

- (void)selectTabbarIndex:(int)index {
    [self.tabBarMain selectIndex:index];
}

#pragma mark - 设置分享SDK
- (void)setupShareSDK
{
    [ShareSDK registerApp:@"19999cbbb2237" activePlatforms:@[
                                                             @(SSDKPlatformTypeSinaWeibo),
                                                             @(SSDKPlatformTypeWechat),
                                                             @(SSDKPlatformTypeQQ)]
                 onImport:^(SSDKPlatformType platformType) {
                     switch (platformType)
                     {
                         case SSDKPlatformTypeWechat:
                             [ShareSDKConnector connectWeChat:[WXApi class]];
                             break;
                         case SSDKPlatformTypeQQ:
                             [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                             break;
                         case SSDKPlatformTypeSinaWeibo:
                             [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                             break;
                         default:
                             break;
                     }
                 } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
                     switch (platformType)
                     {
                         case SSDKPlatformTypeSinaWeibo:
                             // 设置新浪:其中authType设置为使用SSO＋Web形式授权
                             [appInfo SSDKSetupSinaWeiboByAppKey:@"139626686"appSecret:@"2f5625d5f72b19126c43a4650796a5a7"redirectUri:@"http://www.baidu.com"
                                                        authType:SSDKAuthTypeBoth];
                             break;
                             
                             // 设置微信:单一授权
                         case SSDKPlatformTypeWechat:
                             [appInfo SSDKSetupWeChatByAppId:@"wx7b73d0064794d588" appSecret:@"2bf22d9f8bef01e1a9be57fa8202c7c4"];
                             break;
                             
                             // 设置QQ:SSO＋Web形式授权
                         case SSDKPlatformTypeQQ: // 暂时没有注册QQ开发者
                             //41DD38F3
                             [appInfo SSDKSetupQQByAppId:@"1105819119" appKey:@"iVnj0MpqGXBD11Uw"
                                                authType:SSDKAuthTypeBoth];
                             break;
                         default:
                             break;
                     }
                 }];
    
}

#pragma mark - 配置用户通知中心
/**
 * 初始化UNUserNotificationCenter
 */
- (void)registerForRemoteNotification {
    // iOS10 兼容
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        // 使用 UNUserNotificationCenter 来管理通知
        UNUserNotificationCenter *uncenter = [UNUserNotificationCenter currentNotificationCenter];
        // 监听回调事件
        [uncenter setDelegate:self];
        //iOS10 使用以下方法注册，才能得到授权
        [uncenter requestAuthorizationWithOptions:(UNAuthorizationOptionAlert+UNAuthorizationOptionBadge+UNAuthorizationOptionSound)
                                completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                    [[UIApplication sharedApplication] registerForRemoteNotifications];
                                    //TODO:授权状态改变
                                    KLog(@"%@" , granted ? @"授权成功" : @"授权失败");
                                }];
        // 获取当前的通知授权状态, UNNotificationSettings
        [uncenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            NSLog(@"%s\nline:%@\n-----\n%@\n\n", __func__, @(__LINE__), settings);
            /*
             UNAuthorizationStatusNotDetermined : 没有做出选择
             UNAuthorizationStatusDenied : 用户未授权
             UNAuthorizationStatusAuthorized ：用户已授权
             */
            if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
                KLog(@"未选择");
            } else if (settings.authorizationStatus == UNAuthorizationStatusDenied) {
                KLog(@"未授权");
            } else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
                KLog(@"已授权");
            }
        }];
    }
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        UIUserNotificationType types = UIUserNotificationTypeAlert |
        UIUserNotificationTypeBadge |
        UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        UIRemoteNotificationType types = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeAlert |
        UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:types];
    }
#pragma clang diagnostic pop
}

#pragma mark - 每次成功注册通知后调用
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [AVOSCloud handleRemoteNotificationsWithDeviceToken:deviceToken];
}

// 清除 Badge
- (void)applicationDidBecomeActive:(UIApplication *)application {
    NSInteger num=application.applicationIconBadgeNumber;
    if(num!=0){
        AVInstallation *currentInstallation = [AVInstallation currentInstallation];
        [currentInstallation setBadge:0];
        [currentInstallation saveEventually];
        application.applicationIconBadgeNumber=0;
    }
    [application cancelAllLocalNotifications];
    //...
}

#pragma mark - 响应通知数据
// ---------------------------------------------------- iOS 10 + ---------------------------------------------------------------
/**
 * Required for iOS10+
 * 在前台收到推送内容, 执行的方法
 */
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSDictionary *userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //TODO:处理远程推送内容
        KLog(@"%@", userInfo);
    }
    // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
    completionHandler(UNNotificationPresentationOptionAlert);
}

/**
 * Required for iOS10+
 * 在后台和启动之前收到推送内容, 点击推送内容后，执行的方法
 */
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler {
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //TODO:处理远程推送内容
        KLog(@"%@", userInfo);
    }
    completionHandler();
}
// ---------------------------------------------------- iOS 10 + ---------------------------------------------------------------

// 通知到达的时候，你的应用已经在运行
/*!
 * Required for iOS 7+
 */

/*
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
    // Create empty photo object
    NSString *photoId = [userInfo objectForKey:@"p"];
    AVObject *targetPhoto = [AVObject objectWithoutDataWithClassName:@"Photo"
                                                            objectId:photoId];
    
    // Fetch photo object
    [targetPhoto fetchIfNeededInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        // Show photo view controller
        if (error) {
            handler(UIBackgroundFetchResultFailed);
        } else if ([AVUser currentUser]) {
            PhotoVC *viewController = [[PhotoVC alloc] initWithPhoto:object];
            [self.navController pushViewController:viewController animated:YES];
        } else {
            handler(UIBackgroundFetchResultNoData);
        }
    }];
}
*/


//-(void)loadConversations{
//    //获取历史会话记录
//    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
//    if (conversations.count == 0) {
//        conversations =  [[EMClient sharedClient].chatManager loadAllConversationsFromDB];
//    }
//    self.conversations = conversations;
//    //显示总的未读数
//    [self showTabBarBadge];
//}

//- (void)showTabBarBadge{
//    NSInteger totalUnreadCount = 0;
//    for (EMConversation *conversation in self.conversations) {
//        totalUnreadCount += [conversation unreadMessagesCount];
//    }
//    //发送未读消息数给setting界面，展示未读数
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"ChatCount" object:[NSString stringWithFormat:@"%ld",(long)totalUnreadCount]];
//}

@end
